<template>
  <view class="cart-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">购物车</text>
    </view>
    
    <!-- 购物车为空提示 -->
    <view class="empty-cart" v-if="Object.keys(groupedProducts).length === 0">
      <image src="/static/icon/empty-cart.png" mode="aspectFit"></image>
      <text>购物车还是空的</text>
      <button class="go-shopping-btn" @click="goToHome">去逛逛</button>
    </view>
    
    <!-- 购物车列表 - 按超市分组 -->
    <view class="cart-content" v-else>
      <!-- 循环每个超市的商品组 -->
      <view class="shop-group" v-for="(group, shopId) in groupedProducts" :key="shopId">
        <!-- 超市信息 -->
        <view class="shop-info">
          <checkbox :checked="isShopSelected(shopId)" @click="toggleShopSelection(shopId)"></checkbox>
          <image :src="getShopImage(shopId)" mode="aspectFill"></image>
          <text class="shop-name">{{group.shopInfo.name}}</text>
        </view>
        
        <!-- 该超市的商品列表 -->
        <view class="product-list">
          <view class="product-item" v-for="(product, index) in group.products" :key="product.uniqueId">
            <checkbox :checked="selectedProducts[product.uniqueId]" @click="toggleProductSelection(product.uniqueId)"></checkbox>
            <image :src="product.imgUrl" mode="aspectFill"></image>
            <view class="product-info">
              <text class="product-name">{{product.name}} {{product.weight || ''}}</text>
              <view class="product-price-control">
                <text class="price">¥{{product.price}}</text>
                <view class="quantity-control">
                  <text class="minus" @click="decreaseCart(product)">-</text>
                  <text class="count">{{cartProducts[product.uniqueId]}}</text>
                  <text class="plus" @click="addToCart(product)">+</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 每个超市的结算栏 -->
        <view class="shop-checkout-bar">
          <view class="total-info">
            <text class="label">总价:</text>
            <text class="amount">¥{{getShopTotal(shopId).toFixed(2)}}</text>
          </view>
          <view class="checkout-btn" @click="goToOrderConfirm(shopId, group.shopInfo)">
            去结算({{getShopCount(shopId)}})
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartProducts: {}, // 购物车数据
      productsInfo: {}, // 商品详情
      selectedProducts: {}, // 选中的商品
      shopInfoList: {} // 存储超市信息
    }
  },
  computed: {
    // 按超市分组的商品
    groupedProducts() {
      const groups = {};
      
      for (const id in this.cartProducts) {
        if (this.cartProducts[id] > 0 && this.productsInfo[id]) {
          const product = this.productsInfo[id];
          const shopId = product.shopId;
          
          if (!groups[shopId]) {
            groups[shopId] = {
              shopInfo: {
                _id: shopId,
                name: product.shopName,
                imgUrl: this.getShopImage(shopId)
              },
              products: []
            };
          }
          
          groups[shopId].products.push(product);
        }
      }
      
      return groups;
    }
  },
  onShow() {
    // 从本地存储加载购物车数据
    const cartData = uni.getStorageSync('cartData');
    const cartProductsInfo = uni.getStorageSync('cartProductsInfo');
    
    if (cartData) {
      this.cartProducts = JSON.parse(cartData);
    }
    
    if (cartProductsInfo) {
      this.productsInfo = JSON.parse(cartProductsInfo);
    }
    
    // 获取超市信息
    this.fetchShopInfo();
    
    // 初始化选中状态
    this.initSelection();
    
    // 检查是否有已完成的订单，如果有则只清除对应的商品
    const completedOrderItems = uni.getStorageSync('completedOrderItems');
    if (completedOrderItems) {
      this.removeCompletedOrderItems(JSON.parse(completedOrderItems));
      uni.removeStorageSync('completedOrderItems');
    }
  },
  
  methods: {
    // 获取超市信息
    fetchShopInfo() {
      uni.request({
        url: 'http://localhost:3000/hotList',
        success: (res) => {
          if (res.statusCode === 200) {
            // 将超市信息存储为对象，方便通过ID查找
            const shopList = {};
            res.data.forEach(shop => {
              shopList[shop._id] = shop;
            });
            this.shopInfoList = shopList;
          }
        }
      });
    },
    
    // 获取超市图片
    getShopImage(shopId) {
      if (this.shopInfoList[shopId]) {
        return this.shopInfoList[shopId].imgUrl;
      }
      
      // 根据超市ID返回不同的默认图片
      if (shopId === '1') {
        return '/static/imgs/walmart.png'; // 沃尔玛图片
      } else if (shopId === '2') {
        return '/static/imgs/yonghui.png'; // 永辉图片
      }
      
      return '/static/imgs/near.png'; // 默认图片
    },
    
    // 初始化选中状态
    initSelection() {
      this.selectedProducts = {};
      for (const id in this.cartProducts) {
        if (this.cartProducts[id] > 0) {
          this.selectedProducts[id] = true;
        }
      }
    },
    
    // 切换商品选中状态
    toggleProductSelection(productId) {
      if (this.selectedProducts[productId]) {
        this.$set(this.selectedProducts, productId, false);
      } else {
        this.$set(this.selectedProducts, productId, true);
      }
    },
    
    // 判断超市是否全选
    isShopSelected(shopId) {
      const products = this.groupedProducts[shopId].products;
      return products.every(product => this.selectedProducts[product.uniqueId]);
    },
    
    // 切换超市全选状态
    toggleShopSelection(shopId) {
      const products = this.groupedProducts[shopId].products;
      const allSelected = this.isShopSelected(shopId);
      
      products.forEach(product => {
        this.$set(this.selectedProducts, product.uniqueId, !allSelected);
      });
    },
    
    // 获取超市商品总价
    getShopTotal(shopId) {
      let total = 0;
      const group = this.groupedProducts[shopId];
      
      if (group) {
        group.products.forEach(product => {
          if (this.selectedProducts[product.uniqueId]) {
            total += product.price * this.cartProducts[product.uniqueId];
          }
        });
      }
      
      return total;
    },
    
    // 获取超市选中商品数量
    getShopCount(shopId) {
      let count = 0;
      const group = this.groupedProducts[shopId];
      
      if (group) {
        group.products.forEach(product => {
          if (this.selectedProducts[product.uniqueId]) {
            count += this.cartProducts[product.uniqueId];
          }
        });
      }
      
      return count;
    },
    
    // 增加商品数量
    addToCart(product) {
      const id = product.uniqueId;
      this.cartProducts[id]++;
      this.saveCartData();
    },
    
    // 减少商品数量
    decreaseCart(product) {
      const id = product.uniqueId;
      if (this.cartProducts[id] > 1) {
        this.cartProducts[id]--;
      } else {
        this.$delete(this.cartProducts, id);
        this.$delete(this.selectedProducts, id);
        this.$delete(this.productsInfo, id);
      }
      this.saveCartData();
    },
    
    // 保存购物车数据
    saveCartData() {
      uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
      uni.setStorageSync('cartProductsInfo', JSON.stringify(this.productsInfo));
    },
    
    // 跳转到订单确认页面
    goToOrderConfirm(shopId, shopInfo) {
      // 获取完整的超市信息
      let fullShopInfo = this.shopInfoList[shopId];
      
      // 如果没有获取到完整信息，使用默认信息
      if (!fullShopInfo) {
        fullShopInfo = {
          _id: shopId,
          name: shopInfo.name,
          imgUrl: this.getShopImage(shopId),
          expressPrice: 5,
          expressLimit: 0,
          sales: 10000,
          slogan: 'VIP尊享满89元减4元运费券'
        };
      }
      
      // 保存店铺信息
      uni.setStorageSync('shopInfo', JSON.stringify(fullShopInfo));
      
      // 只保存当前超市的选中商品
      const currentShopCart = {};
      const currentShopProducts = {};
      const itemsToRemove = []; // 记录要移除的商品ID
      
      const group = this.groupedProducts[shopId];
      if (group) {
        group.products.forEach(product => {
          if (this.selectedProducts[product.uniqueId]) {
            currentShopCart[product.uniqueId] = this.cartProducts[product.uniqueId];
            currentShopProducts[product.uniqueId] = product;
            itemsToRemove.push(product.uniqueId); // 添加到待移除列表
          }
        });
      }
      
      // 保存当前超市的购物车数据
      uni.setStorageSync('currentOrderCart', JSON.stringify(currentShopCart));
      uni.setStorageSync('currentOrderProducts', JSON.stringify(currentShopProducts));
      uni.setStorageSync('itemsToRemove', JSON.stringify(itemsToRemove)); // 保存待移除列表
      
      // 跳转到订单确认页面，传递shopId参数
      uni.navigateTo({
        url: `/pages/order/order-confirm?shopId=${shopId}`
      });
    },
    
    // 新增方法：移除已完成订单的商品
    removeCompletedOrderItems(itemIds) {
      if (Array.isArray(itemIds) && itemIds.length > 0) {
        itemIds.forEach(id => {
          if (this.cartProducts[id]) {
            this.$delete(this.cartProducts, id);
            this.$delete(this.selectedProducts, id);
            this.$delete(this.productsInfo, id);
          }
        });
        
        // 保存更新后的购物车数据
        this.saveCartData();
      }
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
}
</script>

<style lang="scss">
.cart-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  
  .back-btn {
    margin-right: 20rpx;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
    color: #333;
  }
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;
  
  image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
    opacity: 0.8;
  }
  
  text {
    font-size: 30rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .go-shopping-btn {
    background-color: #0086ff;
    color: #fff;
    font-size: 30rpx;
    padding: 15rpx 50rpx;
    border-radius: 40rpx;
    box-shadow: 0 5rpx 15rpx rgba(0, 134, 255, 0.3);
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
      box-shadow: 0 2rpx 8rpx rgba(0, 134, 255, 0.3);
    }
  }
}

.cart-content {
  padding: 20rpx;
}

.shop-group {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.shop-info {
  display: flex;
  align-items: center;
  padding: 25rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  checkbox {
    margin-right: 20rpx;
    transform: scale(0.9);
  }
  
  image {
    width: 70rpx;
    height: 70rpx;
    border-radius: 10rpx;
    margin-right: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
  
  .shop-name {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
  }
}

.product-list {
  .product-item {
    display: flex;
    align-items: center;
    padding: 25rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    checkbox {
      margin-right: 20rpx;
      transform: scale(0.9);
    }
    
    image {
      width: 180rpx;
      height: 180rpx;
      border-radius: 12rpx;
      margin-right: 25rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    }
    
    .product-info {
      flex: 1;
      
      .product-name {
        font-size: 30rpx;
        margin-bottom: 25rpx;
        color: #333;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .product-price-control {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 34rpx;
          color: #ff5252;
          font-weight: bold;
        }
        
        .quantity-control {
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 60rpx;
            height: 60rpx;
            line-height: 56rpx;
            text-align: center;
            border-radius: 50%;
            border: 1rpx solid #eee;
            font-size: 30rpx;
            background-color: #f8f8f8;
            
            &:active {
              opacity: 0.8;
            }
          }
          
          .count {
            margin: 0 25rpx;
            font-size: 30rpx;
            min-width: 40rpx;
            text-align: center;
          }
          
          .plus {
            background-color: #0086ff;
            color: #fff;
            border: none;
          }
        }
      }
    }
  }
}

.shop-checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  
  .total-info {
    font-size: 30rpx;
    font-weight: bold;
    
    .label {
      color: #333;
      margin-right: 10rpx;
    }
    
    .amount {
      color: #ff5252;
    }
  }
  
  .checkout-btn {
    background: linear-gradient(to right, #0086ff, #00a1ff);
    color: #fff;
    padding: 15rpx 40rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    font-weight: bold;
    box-shadow: 0 5rpx 15rpx rgba(0, 134, 255, 0.3);
    
    &:active {
      opacity: 0.9;
    }
  }
}
</style>